package interact

import (
	"encoding/json"
	"errors"
	"log"
	"path"
	"path/filepath"

	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/config"
	"smartconn.cc/tosone/ra_main/store"
)

var setting map[string]interface{}

var defaultSetting = map[string]interface{}{
	"maxRecording":          8,
	"saidWrong":             globalSettingSaidWrong{Sound: "", Hash: ""},
	"saidNothing":           globalSettingSaidNothing{Sound: "", Hash: ""},
	"noRecord":              false,
	"readOver":              globalSettingReadOver{Sound: "", Hash: ""},
	"retryAsk":              globalSettingRetryAsk{Time: 4},
	"continuousBackinWords": globalSettingContinuousBackinWords{Num: 3, RetryReset: true, Sound: "", Hash: ""},
	"continuousBackSlience": globalSettingContinuousBackSlience{Num: 3, Sound: "", Hash: ""},
}

func mixSetting(g globalSetting) { // mix defautl setting and personal setting
	if g.MaxRecording == 0 {
		setting["maxRecording"] = defaultSetting["maxRecording"]
	}

	if g.SaidNothing.Sound == "" { // search sound if exist or not and replace it default
		setting["saidNothing"] = defaultSetting["saidNothing"]
	} else if g.SaidNothing.Hash != "" && g.SaidNothing.Sound != "" {
		setting["saidNothing"] = g.SaidNothing.Sound
	}

	if g.SaidWrong.Sound == "" {

	}
}

func globalSearchAudio(data interface{}) (interface{}, error) {
	switch data.(type) {
	case globalSetting:
		var g globalSetting
		if data.(globalSetting).SaidNothing.Sound != "" && data.(globalSetting).SaidNothing.Hash != "" {
			if isExist := store.IsTipsAudioExist(data.(globalSetting).SaidNothing.Hash); isExist != "" { // local find this audio
				g.SaidNothing.Sound = isExist
			} else {
				fileDest := path.Join(config.TipsAudio, common.UUID(), filepath.Ext(data.(globalSetting).SaidNothing.Sound))
				task := common.TaskContentDownload{File: data.(globalSetting).SaidNothing.Sound, Path: fileDest, Uncompress: false, StoreTipsAudioHash: data.(globalSetting).SaidNothing.Hash}
				taskStr, err := json.Marshal(task)
				if err != nil {
					log.Println(err)
				}
				store.AddTask("download", string(taskStr))
			}
		}
		return g, nil
	case [][]questionSetting:
		var q [][]questionSetting
		return q, nil
	}
	return "", errors.New("Cannot determine type")
}
